package com.oktest.measure.ui.fragment.work

import android.Manifest
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.cali.common.kt.jsonBody
import com.cali.common.kt.registerEventObj
import com.cali.common.kt.value
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.entity.Type
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.resultListTryContext
import com.oktest.measure.kt.resultTryContext
import com.oktest.measure.media.video.VideoItem
import com.oktest.measure.media.video.VideoPlayActivity
import com.oktest.measure.media.video.VideoPlayActivity.Companion.FILE_PATH
import com.oktest.measure.media.video.adapter.MultiGridAddAdapter
import com.oktest.measure.ui.fragment.work.VideoFragment.Companion.VIDEO_ITEM
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.fragment_work_feedback.*
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import top.zibin.luban.Luban
import java.io.File

/**
 * @Author hhh
 * @Date 2020/9/23
 */
class FeedbackFragment : BaseFragment() {

    companion object {
        const val MEASURE_ID = "measure_id"
    }

    private val api = RetrofitManagement.instance.getService(Api::class.java)

    private val videoAdapter by lazy {
        MultiGridAddAdapter(arrayListOf())
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_work_feedback
    }

    private val rxPermission by lazy {
        RxPermissions(activity!!)
    }

    private var type = Type()

    override fun initData(savedInstanceState: Bundle?) {
        val subscribe = rxPermission.request(Manifest.permission.CAMERA)
                .subscribe {
                    if (it) {
                        initListener()
                    }
                }
        val measureId = arguments?.getLong(MEASURE_ID) ?: 0
        val measure = MyApp.roomDatabase.measureDao().load(measureId)
        type = measure?.parentType() ?: Type()
        tvMeasureName.text = type.name
    }

    private fun initListener() {
        toolbarHelper?.apply {
            setTitleText("问题反馈")
        }
        initVideoRecyclerView()
        // 视频
        registerEventObj<FeedbackFragment, VideoItem>(VIDEO_ITEM) {
            it.type = VideoItem.TYPE_ITEM
            val size = videoAdapter.data.size
            videoAdapter.addData(size - 1, it)
            if (size == 2) {
                videoAdapter.removeAt(2)
            }
        }
        // 提交反馈
        btnCommitFeedback.setOnClickListener {
            if (etFeedback.value().isEmpty()) {
                toast("请输入问题描述")
                return@setOnClickListener
            }
            uploadFeedback()
        }
    }

    private fun uploadFeedback() = launch {
        val compressDir = File(mContext.filesDir, "compress")
        if(!compressDir.exists()) compressDir.mkdirs()
        showTip("正在提交数据..")
        val ids = arrayListOf<String>()
        val imageLists = imageGridView.getImagePath()
        val resultList = resultListTryContext {
            Luban.with(mContext)
                .load(imageLists)
                .ignoreBy(150)
                .setTargetDir(compressDir.absolutePath)
                .get()
        }
        resultList.forEachIndexed { index, file ->
            val multipartBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
            val fileName = file.name
            val fileBody = RequestBody.create(MediaType.parse("image/jpg"), file)
            multipartBuilder.addFormDataPart("files", fileName, fileBody)
            val fileResult = resultTryContext {
                api.feedbackFile(multipartBuilder.build().parts()).execute().body()
            }
            if (fileResult.code == API_SUCCESS_CODE) {
                ids.add(fileResult.data?.ids ?: "")
            }
        }
        uploadText(ids.joinToString(",") { it })
    }

    private fun uploadText(ids: String) = launch {
        val feedResult = resultTryContext {
            val map = hashMapOf<String, Any>()
            map["id"] = MyApp.currentTaskId
            map["mId"] = type.id
            map["image"] = ids
            map["memberId"] = MyApp.memberId
            map["question"] = etFeedback.value()
            api.taskFeedback(map.jsonBody()).execute().body()
        }
        dismissTip()
        if (feedResult.code == API_SUCCESS_CODE) {
            toast("反馈已提交")
            clearContent()
        } else {
            toast("反馈提交失败！")
        }
    }

    private fun clearContent() {
        imageGridView.clear()
        etFeedback.setText("")
    }

    private fun initVideoRecyclerView() {
        videoRecyclerView.apply {
            adapter = videoAdapter
            layoutManager = GridLayoutManager(context, 3)
        }
        videoAdapter.addChildClickViewIds(R.id.ivClose)
        videoAdapter.addData(0, VideoItem(type = VideoItem.TYPE_ADD))
        videoAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == videoAdapter.data.size - 1) {
                // 获取视频
                start(VideoFragment())
            } else {
                // 预览
                val intent = Intent(context, VideoPlayActivity::class.java)
                val videoItem = videoAdapter.getItem(position)
                intent.putExtra(FILE_PATH, videoItem.path)
                context?.startActivity(intent)
            }
        }
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivClose) {
                videoAdapter.removeAt(position)
                val size = videoAdapter.data.size
                if (size == 1 && videoAdapter.data.last().type != VideoItem.TYPE_ADD) {
                    videoAdapter.addData(VideoItem(type = VideoItem.TYPE_ADD))
                }
            }
        }

    }

    override fun hasToolbar(): Boolean {
        return true
    }

    override fun hasBackIcon(): Boolean {
        return true
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        super.onFragmentResult(requestCode, resultCode, data)
        imageGridView.onActivityResult(requestCode, resultCode, data)
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }
}